import { createStore } from 'vuex'//导入createStore构造函数
import { getPostgraduate, getFarmer, graduatelogout, farmerlogout } from '@/api/home'
export default createStore({ 
    state:{ //Vuex的状态，实际上就是存数据的地方
        islogin:false,
		userinfo: {}
    },
    getters:{ //提供获取Vux状态的方式, 注意在组件中调用时getPerson是以属性的方式被访问
        getIslogin(state){
            return state.islogin
        }
    },
    mutations:{ //提供直接操作Vuex的方法，注意mutations里的方法中不能有任何异步操做
        setIslogin(state, value){
            state.islogin = value
        },
		setUserinfo(state, value){
		    state.userinfo = value
		}
    },
    actions:{ //提供通过mutations方法来简介操作Vuex的方法
        async getUserInfo({state, commit}, payload){
            let ret = null
            if(payload.roleType === "POSTGRADUATE") {
                ret = await getPostgraduate({
                    postgraduateId: payload.userId
                })
            } else {
                ret = await getFarmer({
                    farmerId: payload.userId
                })
            }
            if(ret?.code == '200') {
                commit('setUserinfo', {
                    ...ret?.data,
                    uid: payload.userId,
                    roleType: payload.roleType,
                });
                commit('setIslogin', true);
            } else {
                commit('setUserinfo', {
                    uid: payload.userId,
                    roleType: payload.roleType,
                    userName: payload.userName
                });
                commit('setIslogin', true);
            }
        },
        async logout ({state, commit}, payload){
            let ret = null;
            if(state?.userinfo?.roleType === "POSTGRADUATE") {
                ret = await graduatelogout({
                    postgraduateId: state?.userinfo?.uid
                })
            } else {
                ret = await farmerlogout({
                    farmerId: state?.userinfo?.uid
                })
            }
            if(ret?.code == '200') {
                localStorage.removeItem('userInfo_keji')
                location.reload();
            }
        }

    }, 
})
